package com.villaday.idf.util;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.m7.imkfsdk.utils.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.AppContext;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.model3.AllPostersEntity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ShareUtilse {
    public static String IMAGE_NAME = "adf_share_";

    /**
     * @param flag 0分享给微信好友  1分享到朋友圈
     */
    public static void shareImage(final Context context, final int flag, final List<String> images, final String isHightWXNeedShare, final String des) {

        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.ID.WeChat_APP_ID, true);
        api.registerApp(Constant.ID.WeChat_APP_ID);
        if (!api.isWXAppInstalled()) {//未安装微信
            ToastUtil.initToast(context, "您未安装微信");

        } else {
            final List<File> files = new ArrayList<>();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //这一步一定要clear,不然分享了朋友圈马上分享好友图片就会翻倍
                    files.clear();

                    try {
                        Intent intent = new Intent();
                        ComponentName comp;
                        if (flag == 0) {//flag 0分享给微信好友
                            for (int i = 0; i < images.size(); i++) {
                                File file = saveImageToSdCard(context, images.get(i), false);
                                files.add(file);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                            ArrayList<Uri> imageUris = new ArrayList<Uri>();
                            for (File f : files) {
                                imageUris.add(Uri.fromFile(f));
                            }
                            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                        } else {//1分享到朋友圈
                            if (AppContext.isHightWX) {
                                File file = saveImageToSdCard(context, isHightWXNeedShare, false);
                                intent.setAction(Intent.ACTION_SEND);
                                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));


                            } else {
                                for (int i = 0; i < images.size(); i++) {
                                    File file = saveImageToSdCard(context, images.get(i), false);
                                    files.add(file);
                                }
                                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                                for (File f : files) {
                                    imageUris.add(Uri.fromFile(f));
                                }

                                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                            intent.putExtra("Kdescription", des);
                        }
                        intent.setComponent(comp);
                        intent.setType("image/*");

                        context.startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }


    }


    /**
     * @param flag 0分享给微信好友  1分享到朋友圈
     */
    public static void shareImage(final LoadingSaveDialog loadingDialog, final Context context, final int flag, final List<String> images, final String isHightWXNeedShare, final String description) {

        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.ID.WeChat_APP_ID, true);
        api.registerApp(Constant.ID.WeChat_APP_ID);
        if (!api.isWXAppInstalled()) {//未安装微信
            ToastUtil.initToast(context, "您未安装微信");

        } else {
            final List<File> files = new ArrayList<>();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //这一步一定要clear,不然分享了朋友圈马上分享好友图片就会翻倍
                    files.clear();

                    try {
                        Intent intent = new Intent();
                        ComponentName comp;
                        if (flag == 0) {//flag 0分享给微信好友
                            for (int i = 0; i < images.size(); i++) {
                                File file = saveImageToSdCard(context, images.get(i), false);
                                files.add(file);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                            ArrayList<Uri> imageUris = new ArrayList<Uri>();
                            for (File f : files) {
                                imageUris.add(Uri.fromFile(f));
                            }
                            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                        } else {//1分享到朋友圈
                            if (AppContext.isHightWX) {
                                File file = saveImageToSdCard(context, isHightWXNeedShare, false);
                                intent.setAction(Intent.ACTION_SEND);
                                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));


                            } else {
                                for (int i = 0; i < images.size(); i++) {
                                    File file = saveImageToSdCard(context, images.get(i), false);
                                    files.add(file);
                                }
                                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                                for (File f : files) {
                                    imageUris.add(Uri.fromFile(f));
                                }

                                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                            }
                            comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                            intent.putExtra("Kdescription", description);
                        }
                        intent.setComponent(comp);
                        intent.setType("image/*");

                        context.startActivity(intent);

                        if (loadingDialog != null) {
                            loadingDialog.dismiss();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }


    }

    //根据网络图片url路径保存到本地
    public static File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = new File(Environment.getExternalStorageDirectory().getPath() + "/爱订房/" );
        storageDir.mkdir();
        File image = new File(storageDir, imageFileName);
        return image;
    }


    /**
     * 分享文本到微信好友
     *
     * @param context context
     * @param content 需要分享的文本
     */
    public static void shareTextToWeChat(Context context, String content, int type) {
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.ID.WeChat_APP_ID, true);
        api.registerApp(Constant.ID.WeChat_APP_ID);
        if (!api.isWXAppInstalled()) {//未安装微信
            ToastUtil.initToast(context, "您未安装微信");
        } else {
            if (type == 1) {
                //初始化一个 WXTextObject 对象，填写分享的文本内容
                WXTextObject textObj = new WXTextObject();
                textObj.text = content;

                //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = textObj;
                msg.description = content;

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
                //调用api接口，发送数据到微信
                api.sendReq(req);
            } else {
//                Intent intent = new Intent();
//                ComponentName cop = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
//                intent.setComponent(cop);
//                intent.setAction(Intent.ACTION_SEND);
//                intent.putExtra(Intent.EXTRA_TEXT, content);
//                intent.putExtra("Kdescription", "shareTextToWechatFriend");
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                context.startActivity(intent);

                Intent intent = new Intent(Intent.ACTION_MAIN);
                ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(cmp);
                context.startActivity(intent);
            }
        }
    }


    private void shareXCX(Context context, AllPostersEntity.BodyBean.ShareBean shareBean, String xcXimageFileName) {

        File externalCacheDir = context.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + xcXimageFileName;


        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = shareBean.getLink(); // 兼容低版本的网页链接
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        miniProgramObj.userName = shareBean.getMiniAppId();     // 小程序原始id
        miniProgramObj.path = shareBean.getPath();            //小程序页面路径
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBean.getTitle();                 // 小程序消息title
        msg.description = shareBean.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 100 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支持会话
        IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }




    public static void deletePic(Context context, String path) {
        if (!TextUtils.isEmpty(path)) {
            Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            ContentResolver contentResolver = context.getContentResolver();//cutPic.this是一个上下文
            String url = MediaStore.Images.Media.DATA + "='" + path + "'";
            //删除图片
            contentResolver.delete(uri, url, null);
        }
    }


    /**
     * 删除文件
     */
    public static void delFile(File file) {
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                    delFile(files[i]); // 把每个文件 用这个方法进行迭代
                }
            }
            file.delete();
        }
    }

}
